import os

from curl_cffi import requests

import csv



headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
    'cookie':'AlteonP10=BDk7GSw/F6wFdM0W+gByLA$$; apache=bbfde8c184f3e1c6074ffab28a313c87; ags=2a1ba4d47b619c011c19c1cc4b3c0c32; _ulta_id.ECM-Prod.ccc4=6ccc5efa042d9ae8; _ulta_ses.ECM-Prod.ccc4=532d5687f9dc4968',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Referer':'https: // iftp.chinamoney.com.cn / english / bdInfo /'
}


file_path = "python开发测试第一题结果.csv"


def qingqiu(data):
    url = "https://iftp.chinamoney.com.cn/ags/ms/cm-u-bond-md/BondMarketInfoListEN"
    resp = requests.post(url, data=data,headers=headers, verify=False )

    csv_head = [['ISIN', 'Bond Code', 'Issuer', 'Bond Type', 'Issue Date', 'Latest Rating']]

    data = resp.json()
    middle_data = data['data']['resultList']

    result = []
    for data in middle_data:

        ISIN = data['isin']
        BondCode = data['bondCode']
        Issuer = data['entyFullName']
        BondType = data['bondType']
        IssueDate = data['issueStartDate']
        LatestRating = data['debtRtng']
        result.append([ISIN, BondCode, Issuer, BondType, IssueDate, LatestRating])
    print(result)




    if not os.path.exists(file_path):
        with open(file_path, mode='w', newline='', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerows(csv_head)
            writer.writerows(result)

        print(f"数据已保存为 CSV 文件，路径为：{file_path}")

    else:

        with open(file_path, 'a+', newline='', encoding='utf-8') as csvfile:
            csvwriter = csv.writer(csvfile)
            csvwriter.writerows(result)
        print(f"数据已保存到 {file_path} 文件中")



if __name__ == '__main__':
    page = int(input('请输入你要爬取的页数：'))
    for i  in range(1, page + 1):
        data = {
            'pageNo': i,
            'pageSize': 15,
            'isin': '',
            'bondCode': '',
            'issueEnty': '',
            'bondType': 100001,
            'couponType': '',
            'issueYear': 2023,
            'rtngShrt': '',
            'bondSpclPrjctVrty': '',

        }
        print(f'正在爬取第{i}页')
        resp = qingqiu(data)